package com.imooc.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.imooc.config.ProjectUrlConfig;
import com.imooc.utils.HttpClient;
import com.imooc.utils.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

/**
 * 测试微信扫码支付生成
 */
@Controller
@RequestMapping("/qrCodePay")
@Slf4j
public class WxTestQrCodePayController {
    
    @Autowired
    private ProjectUrlConfig projectUrlConfig;
    
    private String appid="wx8397f8696b538317";
    
    private String partner="1473426802";
    
    private String partnerkey="8A627A4578ACE384017C997F12D68B23";
    
    private String notifyurl="http://xxx/WeChatPay/WeChatPayNotify";
    
    /**
     * 去扫码支付页面
     * http://localhost:8080/sell/payPagePC/pay.html
     */
    @RequestMapping("/orderNoQrCode")
    public String orderNoQrCode() {
        log.info("去扫码支付页面");
        return "redirect:"+projectUrlConfig.getWechatMpAuthorize()+"/sell/payPagePC/pay.html";
    }
    
    /**
     * 去扫码支付页面
     * http://localhost:8080//sell/qrCodePay/payfail
     */
    @RequestMapping("/payfail")
    public String payfail() {
        log.info("去支付失败页面");
        return "redirect:"+projectUrlConfig.getWechatMpAuthorize()+"/sell/payPagePC/payfail.html";
    }
    
    /**
     * 去支付成功页面
     * http://localhost:8080//sell/qrCodePay/paysuccess
     */
    @RequestMapping("/paysuccess")
    public String paysuccess() {
        log.info("去支付成功页面");
        return "redirect:"+projectUrlConfig.getWechatMpAuthorize()+"/sell/payPagePC/paysuccess.html";
    }
    
    
    /**
     * 获取订单信息页面
     * http://域名/sell/qrCodePay/getOrderInfo
     */
    @RequestMapping("/getOrderInfo")
    public String getOrderInfo() {
        log.info("获取订单信息页面");
        return "redirect:"+projectUrlConfig.getWechatMpAuthorize()+"/sell/payPagePC/getOrderInfo.html";
    }
    
    
    @RequestMapping("/createNative")
    public Map createNative(){
//        //1.获取当前登录用户
//        String username = SecurityContextHolder.getContext().getAuthentication().getName();
//        //2.提取支付日志（从缓存 ）
//        TbPayLog payLog = orderService.searchPayLogFromRedis(username);
//        //3.调用微信支付接口
//        if(payLog!=null){
//            return weixinPayService.createNative(payLog.getOutTradeNo(), payLog.getTotalFee()+"");
//        }else{
//            return new HashMap<>();
//        }
    
        IdWorker idWorker = new IdWorker();
    
        Map map = createNative(idWorker.nextId() + "", 1 + "");
        return map;
    }
    
    public Map createNative(String out_trade_no, String total_fee) {
        //1.参数封装
        Map param=new HashMap();
        param.put("appid", appid);//公众账号ID
        param.put("mch_id", partner);//商户
        param.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
        param.put("body", "xxx商城");
        param.put("out_trade_no", out_trade_no);//交易订单号
        param.put("total_fee", total_fee);//金额（分）
        param.put("spbill_create_ip", "127.0.0.1");
        param.put("notify_url", "http://www.itcast.cn");
        param.put("trade_type", "NATIVE");//交易类型
        
        try {
            String xmlParam = WXPayUtil.generateSignedXml(param, partnerkey);
            System.out.println("请求的参数："+xmlParam);
            
            //2.发送请求
            HttpClient httpClient=new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setHttps(true);
            httpClient.setXmlParam(xmlParam);
            httpClient.post();
            
            //3.获取结果
            String xmlResult = httpClient.getContent();
            
            Map<String, String> mapResult = WXPayUtil.xmlToMap(xmlResult);
            System.out.println("微信返回结果"+mapResult);
            Map map=new HashMap<>();
            map.put("code_url", mapResult.get("code_url"));//生成支付二维码的链接
            map.put("out_trade_no", out_trade_no);
            map.put("total_fee", total_fee);
            
            return map;
            
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap();
        }
        
    }
    

    public Map queryPayStatus(String out_trade_no) {
        //1.封装参数
        Map param=new HashMap();
        param.put("appid", appid);
        param.put("mch_id", partner);
        param.put("out_trade_no", out_trade_no);
        param.put("nonce_str", WXPayUtil.generateNonceStr());
        try {
            String xmlParam = WXPayUtil.generateSignedXml(param, partnerkey);
            //2.发送请求
            HttpClient httpClient=new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setHttps(true);
            httpClient.setXmlParam(xmlParam);
            httpClient.post();
            
            //3.获取结果
            String xmlResult = httpClient.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(xmlResult);
            System.out.println("调动查询API返回结果："+xmlResult);
            
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        
    }
    
}
